//
//  LoginViewController.swift
//  ShareCar
//
//  Created by lishuai on 2018/6/25.
//  Copyright © 2018年 changqingkeji. All rights reserved.
//

import UIKit
import CryptoSwift
import YYKit

class LoginViewController: UIViewController {
    
    @IBOutlet weak var userInfoView: UIView!
    @IBOutlet weak var codeButton: GSCountdownButton!
    @IBOutlet weak var loginButton: UIButton!
    @IBOutlet weak var phoneField: UITextField!
    @IBOutlet weak var passwordField: UITextField!
    
    var protocolLabel: YYLabel!
    
    var sendCount = 1
    
    // MARK: - view method
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setup()
    }
    
    // MARK: - IBAction
    
    @IBAction func makephoneCode(_ sender: GSCountdownButton) {
        
        sendCount += 1
        
        //判断手机号是否为空
        guard let tel = phoneField.text, isTelNumber(tel) else {
            self.showError("请输入正确的手机号")
            return
        }

        let time = String(NSDate().timeIntervalSince1970)
        let str = "timerent" + (phoneField.text)! + time
        let hash = str.md5().lowercased()
        JZLoading.showLoadingWith(toView: self.view)
        User.makeMessageCode(telephone: tel, time: time, signature: hash, sendCount: sendCount, success: { [weak self] in
            
            JZLoading.hideLoading()
            XHProgressHUD.showSuccess("验证码发送成功")
            
            self?.codeButton.maxSecond = 60
            self?.codeButton.countdown = true
        }) { [weak self] error in
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }
    
    @IBAction func login(_ sender: Any) {
        // 判断手机号是否为空
        guard let tel = phoneField.text, isTelNumber(tel) else {
            XHProgressHUD.showError("请您输入正确手机号后重试(1027)")
            return
        }
        
        // 判断验证码是否为空
        guard let pass = passwordField.text else {
            XHProgressHUD.showError("请您输入验证码后重试(1028)")
            return
        }
        
        guard pass.count > 0 else {
            self.showError("请您输入验证码后重试(1028)")
            return
        }

        JZLoading.showLoadingWith(toView: self.view)
        User.login(telephone: tel, smsCode: pass, success: { [weak self] in
            JZLoading.hideLoading()
            if let user = User.info() {
                
                JPUSHService.setTags(nil, alias: user.userId, fetchCompletionHandle: { (vlaue, temp, t) in
                    print(" ::: ,",vlaue,temp,t)
                })
                self?.dismiss(animated: true, completion: nil)
            } else {
                self?.showError("登录失败")
            }
        }) { [weak self] error in
            JZLoading.hideLoading()
            self?.showError(error)
        }
    }
    
    @objc func a(temp: Any) {
        print("::::",temp)
    }
    
    @IBAction func closeView(_ sender: UIButton) {
        dismiss(animated: true, completion: nil)
    }

    // MARK: - custom method
    
    func isTelNumber(_ num: String) -> Bool {
        
        let mobile = "^(1[3,4,5,6,7,8,9])[0-9]{9}$"
        let regextestmobile = NSPredicate(format: "SELF MATCHES %@", mobile)
        return (regextestmobile.evaluate(with: num))
    }
    
    func setup() {
        let titleInfo = ["type":"0","content":"点击“登录/注册”按钮，表示您已阅读并同意"]
        let registerInfo = ["type":"3","content":"《蜜橙出行注册协议》"]
        let secretInfo = ["type":"8","content":"《蜜橙出行隐私协议》"]
        let array = [titleInfo,registerInfo,secretInfo]
        //拼接字符串
        var strArr = [String]()
        var content1 = String()
        
        for temp in array {
            if let content = temp["content"] {
                strArr.append(content)
            }
        }
        
        let title = strArr.joined(separator: "")
        let text = NSMutableAttributedString(string: title)
        text.font = UIFont.systemFont(ofSize: 14)
        text.lineSpacing = 5;
        
        for var item in array {
            if let type = Int(item["type"]!), type != 0 {
                content1 = item["content"]!
                let range = title.range(of: content1, options: .caseInsensitive, range: nil, locale: nil)
                if let range = range {
                    let rang = title.toNSRange(range)
                    text.setTextHighlight(rang, color: UIColor.init(valueRGB: 0x2d72d9, alpha: 1.0), backgroundColor: UIColor.clear, userInfo: nil, tapAction: { [weak self] (view, text, rang, rect) in
                        let page: H5page
                        page = type == 3 ? .registere : .privacy
                        self?.performSegue(withIdentifier: "webControllerSence", sender: page)
                    })
                }
            }
        }
        
        protocolLabel = YYLabel()
        protocolLabel.numberOfLines = 2
        protocolLabel.font = UIFont.systemFont(ofSize: 12)
        protocolLabel.sizeToFit()
        protocolLabel.attributedText = text
        let height = makeLabelFrameWithHeight(text: title, lineSpace: 5, font: UIFont.systemFont(ofSize: 14), width: kScreenWidth - 40)
        view.addSubview(protocolLabel)
        
        protocolLabel.snp.makeConstraints { make in
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.top.equalTo(loginButton.snp.bottom).offset(20)
            make.height.equalTo(height)
        }
    }
    
    func makeLabelFrameWithHeight(text: String,lineSpace: CGFloat,font: UIFont,width: CGFloat) -> CGFloat {
        let paraStyle = NSMutableParagraphStyle()
        paraStyle.lineBreakMode = .byCharWrapping
        paraStyle.alignment = .left
        paraStyle.lineSpacing = lineSpace
        paraStyle.hyphenationFactor = 1.0
        paraStyle.firstLineHeadIndent = 0.0
        paraStyle.paragraphSpacingBefore = 0.0
        paraStyle.headIndent = 0
        paraStyle.tailIndent = 0
        let dic = [NSAttributedStringKey.font: font, NSAttributedStringKey.paragraphStyle: paraStyle,NSAttributedStringKey.kern: 1.0] as [NSAttributedStringKey : Any]
        let str = text as NSString
        let size = str.boundingRect(with: CGSize(width: width, height: CGFloat(MAXFLOAT)), options: .usesLineFragmentOrigin, attributes: dic, context: nil).size
        return size.height
    }
    
    // MARK: - Navigation
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if segue.identifier == "webControllerSence" {
            guard let nav = segue.destination as? UINavigationController else {
                return
            }
            
            guard let vc = nav.viewControllers.first as? WebViewController else {
                return
            }
            
            if let p = sender as? H5page {
                vc.page = Page.server(p)
            }
        }
    }
}

// MARK: - Text Field Delegate

extension LoginViewController: UITextFieldDelegate {

    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        
        if string.count != 0 {
            if textField.tag == 100 {
                return (textField.text?.count)! < 11
            }
        }
        return true
    }
}


